package com.hucii.app.json;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;

import org.json.JSONException;
import org.json.JSONObject;

public class CXJson {
	
	public CXJsonNode m_pJsonDoc;
	
	//从本地下载
	 public CXJsonNode loadJsonFromNative(String filepath) throws Exception{
		 FileInputStream fileInputStream = new FileInputStream(new File(filepath));
		 InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
		 BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		 StringBuffer strData = new StringBuffer();
		 String data = bufferedReader.readLine();
		 do{
			 strData.append(data);
			 data = bufferedReader.readLine();
		 }while(data!=null);
			JSONObject jSONObject = new JSONObject(strData.toString());
			m_pJsonDoc = new CXJsonNode(jSONObject);
			return m_pJsonDoc;
	 }
	 //从网络下载
	 public CXJsonNode loadJsonFromNet(byte[] aData) throws JSONException{
		String strData = new String(aData);
		JSONObject jSONObject = new JSONObject(strData);
		m_pJsonDoc = new CXJsonNode(jSONObject);
		return m_pJsonDoc;
	 }
	 //创建json的根节点
	 public CXJsonNode createJson(){
		 JSONObject jSONObject = new JSONObject();
		 m_pJsonDoc = new CXJsonNode(jSONObject);
		 return m_pJsonDoc;
	 }
	 //保存json,filepath:保存的路径
	 public boolean save(String filepath){
	    try{
			FileWriter writer = new FileWriter(filepath, false);
		    writer.write(m_pJsonDoc.toNodeString());
		    writer.close();
			return true;
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return false;	
	}
	 //返回CXJson的字符串形势
	public String ToJsonString(){
		return m_pJsonDoc.toNodeString();
	}
}
